<template>
  <div class="container" ref="mainCon">
    <div class="mainCon">
      <el-row class="toolbar searchInputWidth" style="padding-bottom: 0">
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-row>
            <el-col :lg="8" :xl="6">
              <el-form-item label="区域" class="row-padding-bottom">
                <el-cascader
                  v-model="areaId"
                  :options="areasOptions"
                  @change="getAreaId"
                  clearable
                  filterable
                  placeholder="请选择"
                  :props="{ checkStrictly: true }"
                  :append-to-body="false"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="缴纳方式" class="row-padding-bottom">
                <el-select
                  v-model="filterField.depositType"
                  placeholder="请选择"
                  clearable
                  :popper-append-to-body="false"
                >
                  <el-option
                    v-for="item in depositTypeOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-form-item>
              <!-- <el-button type="primary" icon="icon iconfont iconchazhao1"  class="commonBtn" @click = "searchList"></el-button> -->
              <el-button
                type="primary"
                icon="icon iconfont iconchazhao1"
                @click="searchList"
                class="searchBtn"
              >
                <span>搜索</span>
              </el-button>
              <exportBtn
                v-if="!isShowAdd"
                :dataLen="tableData.length"
                :filterField="filterField"
                api="api-s/report/export_JC_CS_DEPOSIT_SET_RATIO"
              ></exportBtn>
            </el-form-item>
            <!-- <el-form-item>
                            <el-button :disabled="isDisabled" class="commonBut saveBtn funComBut addSecondTab" icon="icon iconfont icontianjia" @click = "addPaymentRatio" v-show="isShowAdd">
                                <span class="opetareText">添加</span>  
                            </el-button>
                        </el-form-item> -->
          </el-row>
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <div style="margin-bottom: 24px" v-if="isShowAdd">
          <exportBtn
            :dataLen="tableData.length"
            :filterField="filterField"
            api="api-s/report/export_JC_CS_DEPOSIT_SET_RATIO"
          ></exportBtn>
          <el-button
            :disabled="isDisabled"
            class="commonBut saveBtn funComBut addSecondTab"
            icon="icon iconfont icontianjia"
            @click="addPaymentRatio"
          >
            <span class="opetareText">添加</span>
          </el-button>
        </div>
        <el-table
          ref="tableBox1"
          :max-height="tableHeight"
          :data="tableData"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          style="border: 1px solid #dfe6ec"
          border
          :span-method="objectSpanMethod"
        >
          <el-table-column
            prop="areaName"
            label="区域"
            width="200"
          ></el-table-column>
          <el-table-column
            prop="depositTypeDesc"
            label="缴纳方式"
            width="200"
          ></el-table-column>
          <el-table-column
            prop="isSectionDesc"
            label="分段设置比例"
            align="center"
            min-width="120px"
          ></el-table-column>
          <el-table-column prop="condition" label="条件" width="230">
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.condition"
                :columnName="'condition'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column prop="scale" label="比例" align="center">
            <template slot-scope="scope"> {{ scope.row.scale }}% </template>
          </el-table-column>
          <el-table-column
            prop="upperLimit"
            label="缴纳上限（万元）"
            align="center"
            min-width="180"
          >
            <template slot-scope="scope">
              {{ scope.row.upperLimit ? scope.row.upperLimit : '--' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" width="130" fixed="right">
            <template slot-scope="scope">
              <el-link
                type="primary"
                @click.stop="updateData(scope.$index, scope.row)"
                v-show="isShowUpdate"
                >修改</el-link
              >
              <el-link
                type="primary"
                @click.stop="delData(scope.$index, scope.row)"
                v-show="isShowDel"
                >删除</el-link
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无数据"></emptyTable>
          </div>
        </el-table>
        <Pagination
          ref="pagination"
          @getpageNo="getpageNo"
          @getpageSize="getpageSize"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
        ></Pagination>
      </div>
    </div>
    <el-dialog
      :title="dialogName"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      @close="closeDialog('formData')"
      custom-class="brand-dialog-min-width"
      :modal-append-to-body="false"
      :append-to-body="true"
      width="900px"
    >
      <el-form ref="formData" :model="formData" style="padding-top: 8px">
        <el-form-item
          label="区域："
          :label-width="formLabelCardWidth"
          prop="addAreaId"
          :rules="rules.addAreaId"
        >
          <el-cascader
            class="mWidth"
            v-model="addAreaId"
            :options="areasOptions"
            clearable
            filterable
            placeholder="请选择"
            :props="{ checkStrictly: true }"
            ref="areas"
            @change="getCostAreaId"
            :disabled="disabled"
          ></el-cascader>
        </el-form-item>
        <el-form-item
          label="分段设置比例："
          :label-width="formLabelCardWidth"
          prop="radio"
          :rules="rules.radio"
        >
          <el-radio-group v-model="formData.radio" @change="handleRadio">
            <el-radio label="1" @change="selectNo">否</el-radio>
            <el-radio label="2" @change="selectNo">是</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          label="计算方法1："
          style="margin-bottom: 16px !important"
          v-if="formData.radio == 2"
          :label-width="formLabelCardWidth"
          prop="sectionType"
          :rules="rules.sectionType"
        >
          <el-radio-group v-model="formData.sectionType">
            <el-radio label="0" @change="selectNo"
              >直接工程造价*缴纳比例</el-radio
            >
            <el-radio label="1" @change="selectNo"
              >分段相加求和(每段工程造价*缴纳比例)</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="缴纳方式："
          :label-width="formLabelCardWidth"
          prop="depositType"
          :rules="rules.depositType"
          v-if="formData.radio == '1'"
        >
          <el-select
            v-model="formData.depositType"
            placeholder="请选择"
            class="mWidth"
          >
            <el-option
              v-for="item in depositTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 选择否显示的内容 -->
        <div v-if="formData.radio == '1'">
          <div
            class="segmentSettingNo"
            v-for="(item, i) in formData.scaleList"
            :key="i"
          >
            <el-form-item
              label="缴纳比例："
              :label-width="formLabelCardWidth"
              :prop="'scaleList.' + i + '.scale'"
              class="mB0 projectCostBox"
              :rules="rules.scale"
            >
              <el-input
                v-model="item.scale"
                class="mWidth"
                autocomplete="off"
                placeholder="请输入"
                @blur="item.scale = changeValue($event)"
              ></el-input>
              <span class="unit">%</span>
              <span class="buttonBox">
                <el-link type="primary">
                  <span
                    v-if="
                      hasShowScaleReduce && i === formData.scaleList.length - 1
                    "
                    @click="delScaleList(i)"
                  >
                    <i class="icon iconfont icon-deleteFont"></i>删除</span
                  >
                </el-link>
                <el-link type="primary">
                  <span
                    @click="addScale(i)"
                    v-if="i === formData.scaleList.length - 1"
                  >
                    <i class="icon iconfont icon-addFont"></i>添加</span
                  >
                </el-link>
              </span>
            </el-form-item>
          </div>
          <el-form-item
            label="缴纳上限："
            :label-width="formLabelCardWidth"
            :rules="rules.noPayOnline"
            prop="noPayOnline"
          >
            <el-input
              v-model="formData.noPayOnline"
              autocomplete="off"
              placeholder="请输入"
              class="mWidth"
              @blur="formData.noPayOnline = changeValue($event)"
            ></el-input>
            <span class="unit">万元</span>
          </el-form-item>
        </div>
        <div v-if="formData.radio == '2'">
          <div class="segmentSettingYes">
            <div class="segmentTitle">工程造价范围/缴纳比例</div>
            <el-form-item
              label="工程造价范围："
              :label-width="formLabelCardWidth"
              prop="maxCost"
              class="projectCostBox"
              :rules="rules.maxCost"
            >
              <span>工程造价</span><span class="mL18">&le;</span>
              <el-input
                v-model="formData.maxCost"
                autocomplete="off"
                placeholder="请输入"
                class="unlimitInput mL18"
                @blur="formData.maxCost = changeValue($event)"
                @input="inputMaxCost"
              ></el-input>
              <span class="unit">万元</span>
            </el-form-item>
            <el-form-item
              label="缴纳比例："
              :label-width="formLabelCardWidth"
              prop="firstToPay"
              class="mB0"
              :rules="rules.firstToPay"
            >
              <el-input
                v-model="formData.firstToPay"
                autocomplete="off"
                placeholder="请输入"
                class="mWidth"
                @blur="formData.firstToPay = changeValue($event)"
              ></el-input
              ><span class="unit">%</span>
            </el-form-item>
          </div>
          <div
            class="segmentSettingYes mT12"
            v-for="(item, i) in formData.costList"
            :key="i"
          >
            <div class="segmentTitle">
              工程造价范围/缴纳比例
              <span class="buttonBox">
                <el-link type="primary">
                  <span
                    v-if="i === formData.costList.length - 1"
                    @click="addCostList(i)"
                  >
                    <i class="icon iconfont icon-addFont"></i>添加</span
                  >
                </el-link>
                <el-link type="primary">
                  <span
                    @click="delCostList(i)"
                    v-if="hasShowReduce && i === formData.costList.length - 1"
                  >
                    <i class="icon iconfont icon-deleteFont"></i>删除</span
                  >
                </el-link>
              </span>
            </div>
            <el-form-item
              label="工程造价范围："
              :label-width="formLabelCardWidth"
              class="projectCostBox"
              :prop="'costList.' + i + '.max'"
              :rules="rules.maximumProjectCost"
            >
              <el-input
                v-model="item.min"
                autocomplete="off"
                placeholder="请输入"
                class="unlimitInput"
                @blur="item.min = changeValue($event)"
                disabled
              ></el-input>
              <span class="mL18">&lt;</span>
              <span class="mL18">工程造价</span><span class="mL18">&le;</span>
              <el-input
                v-model="item.max"
                autocomplete="off"
                placeholder="请输入"
                class="unlimitInput mL18"
                @input="assignmentCostMax(i)"
                @blur="item.max = changeValue($event)"
                v-if="i !== formData.costList.length - 1"
                :id="'max' + i"
              ></el-input
              >&nbsp;
              <el-input
                v-model="unlimit"
                autocomplete="off"
                placeholder="请输入"
                class="unlimitInput mL18 unlimitSty"
                @blur="unlimit = changeValue($event)"
                v-if="i == formData.costList.length - 1"
                :id="'max' + i"
                readonly
              ></el-input>
              <span class="unit">万元</span>
            </el-form-item>
            <el-form-item
              label="缴纳比例："
              :label-width="formLabelCardWidth"
              :prop="'costList.' + i + '.scale'"
              class="mB0 projectCostBox"
              :rules="rules.scale"
            >
              <el-input
                v-model="item.scale"
                autocomplete="off"
                placeholder="请输入"
                class="mWidth"
                @blur="item.scale = changeValue($event)"
              ></el-input
              ><span class="unit">%</span>
            </el-form-item>
          </div>
          <div style="margin-top: 24px">
            <el-form-item
              label="缴纳上限："
              :label-width="formLabelCardWidth"
              prop="yesPayOnline"
              :rules="rules.noPayOnline"
            >
              <el-input
                v-model="formData.yesPayOnline"
                autocomplete="off"
                placeholder="请输入"
                class="mWidth"
                @blur="formData.yesPayOnline = changeValue($event)"
              ></el-input
              ><span class="unit">万元</span>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="cancel('formData')" class="cancel"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click.native="saveTopay('formData')"
          class="save"
          :loading="isSaveLoading"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'
//引导页插件
import Driver from 'driver.js' // import driver.js
import 'driver.js/dist/driver.min.css' // import driver.js css
import steps from '../../kits/cashDepositStep'
export default {
  name: 'paymentRatio',
  props: ['fromTag'],
  data() {
    var validateMaxProjectCost = (rule, value, callback) => {
      // value = value.replace(/\s+/g, "");
      var NumValue = Number(value)
      var index = rule.field.slice(9, 10)
      var i = Number(index)
      this.formData.costList[this.formData.costList.length - 1].max =
        '9999999999'
      if (value === '') {
        callback(new Error('工程造价范围不能为空'))
      } else if (NumValue > '9999999999' || NumValue > 9999999999) {
        callback(new Error('工程造价范围不能超过9999999999'))
      } else {
        var regCost = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/
        if (!regCost.test(value) || value == 0.0 || value == 0.0) {
          callback(
            new Error('工程造价范围格式不正确,必须大于0,最多带有2位小数')
          )
        } else {
          this.formData.costList[0].min = this.formData.maxCost
          if (
            Number(this.formData.costList[index].min) > NumValue ||
            Number(this.formData.costList[index].min) == NumValue
          ) {
            var j = i + 1
            $('#max' + j).focus()
            $('#max' + j).blur()
            callback(new Error('最大值不可小于最小值，请重新输入'))
          } else {
            if (
              this.formData.costList[i + 1] &&
              this.formData.costList[i + 1].max
            ) {
              var j = i + 1
              $('#max' + j).focus()
              $('#max' + j).blur()
              callback()
            } else {
              callback()
            }
          }
        }
      }
    }
    var validateToPay = (rule, value, callback) => {
      let array = []
      for (var i = 0; i < this.formData.scaleList.length; i++) {
        if (this.formData.scaleList[i].scale) {
          array.push(Number(this.formData.scaleList[i].scale))
        }
      }
      if (value === '') {
        value = value.replace(/\s+/g, '')
        callback(new Error('缴纳比例不能为空'))
      } else {
        // var regCost = /(?!^0\.0?0$)^[0-9][0-9]?(\.[0-9]{1,2})?$|^100$/;
        var regCost = /^(100|[1-9]\d|\d)(.\d{1,2})?$/
        if (
          !regCost.test(value) ||
          value == 0.0 ||
          value == 0.0 ||
          value > 100
        ) {
          callback(new Error('缴纳比例格式不正确'))
        } else {
          callback()
        }
      }
    }
    var checkArea = (rule, value, callback) => {
      if (!this.addAreaId || this.addAreaId.length < 1) {
        return callback(new Error('请选择区域'))
      } else {
        callback()
      }
    }
    // 验证比例第一个值输入规则
    var maxCost = (rule, value, callback) => {
      // value = value.replace(/\s+/g, "");
      var NumValue = Number(value)
      if (value === '') {
        callback(new Error('工程造价范围不能为空'))
      } else if (NumValue > '9999999999' || NumValue > 9999999999) {
        callback(new Error('工程造价范围不能超过9999999999'))
      } else {
        var regCost = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/
        if (!regCost.test(value) || value == 0.0 || value == 0.0) {
          callback(
            new Error('工程造价范围格式不正确,必须大于0,最多带有2位小数')
          )
        } else {
          if (this.formData.costList[0].max) {
            if (
              NumValue > Number(this.formData.costList[0].max) ||
              NumValue == Number(this.formData.costList[0].max)
            ) {
              $('#max0').focus()
              $('#max0').blur()
              callback()
            } else {
              $('#max0').focus()
              $('#max0').blur()
              callback()
            }
          } else {
            callback()
          }
        }
      }
    }
    var validateNoPayOnline = (rule, value, callback) => {
      var regCost = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/
      if (value == null) {
        value = ''
      }
      if (
        value != '' &&
        (!regCost.test(value) || value == 0.0 || value == 0.0)
      ) {
        callback(new Error('缴纳上限格式不正确,必须大于0,最多带有2位小数'))
      } else if (value > '9999999999' || value > 9999999999) {
        callback(new Error('缴纳上限不能超过9999999999'))
      } else {
        callback()
      }
    }
    return {
      hiddleToolBar: false,
      tableHeight: null,
      input: '',
      isShowAdd: true, //是否显示新增按钮
      //表格数据
      tableData: [],
      paramsList: [],
      depositTypeOptions: [],
      requestUrl: 'api-d/config/expand/list',
      //搜索条件
      isShow: false,
      loading: true,
      rowIndex: '-1',
      OrderIndexArr: [],
      hoverOrderArr: [],
      formVisible: false, //添加缴纳比例显示和隐藏
      formLabelCardWidth: '125px',
      formData: {
        costList: [{ min: '', max: '', scale: '' }],
        maxCost: '', //上线
        firstToPay: '',
        radio: '1', //选择是否
        noToPay: '',
        scale: '',
        areaId: '', //区域
        addAreaId: '',
        noPayOnline: '',
        depositType: '',
        scaleArray: [],
        scaleList: [{ scale: '' }],
        yesPayOnline: '',
      },
      rules: {
        maximumProjectCost: [
          {
            required: true,
            validator: validateMaxProjectCost,
            trigger: 'blur',
          },
        ],
        maxCost: [{ required: true, validator: maxCost, trigger: 'blur' }],
        depositType: [
          { required: true, message: '缴纳方式不能为空', trigger: 'change' },
        ],
        radio: [
          { required: true, message: '分段设置比例不能为空', trigger: 'blur' },
        ],
        scale: [{ required: true, validator: validateToPay, trigger: 'blur' }],
        noToPay: [
          { required: true, validator: validateToPay, trigger: 'blur' },
        ],
        addAreaId: [
          //   { required: true,message: "请选择区域", trigger: "change" }
          {
            required: true,
            validator: checkArea,
            // message: "请选择区域",
            trigger: 'change',
          },
        ],
        firstToPay: [
          { required: true, validator: validateToPay, trigger: 'blur' },
        ],
        noPayOnline: [{ validator: validateNoPayOnline, trigger: 'blur' }],
      },
      hasShowReduce: false,
      filterField: {
        areaId: '', //区域
        depositType: '', //缴纳方式
      },
      pageSize: 20,
      pageNo: 1,
      // noPayOnline: "", //缴纳上限
      // yesPayOnline: "",
      Areas: {
        AreaId: '', //注册地址全id
        AreaName: '', //注册地址全名称
        CityId: '', //注册地址市id
        CityName: '', //注册地址市名称
        CountyId: '', //注册地址区id
        CountyName: '', //注册地址区名称
      },
      unlimit: '无限制',
      isAdd: '', //是否是修改还是添加弹框
      areaId: '',
      addAreaId: '',
      dialogName: '', //弹框title
      disabled: true,
      isSaveLoading: false,
      isShowDel: '',
      isShowUpdate: '',
      isShowAdd: '',
      isDisabled: false,
      hasShowScaleReduce: false,

      oldDepositType: '',
    }
  },
  computed: { ...mapState(['areasOptions']) },
  created() {
    //缴纳方式
    this.getDepositTypeDesc()
    this.getAreas({ areaId: this.$store.state.areaInfoArr.areaId })
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    this.isShowAdd =
      this.$store.state.buttonLimitsArr.indexOf('depositSet:add') > -1
    this.isShowUpdate =
      this.$store.state.buttonLimitsArr.indexOf('depositSet:update') > -1
    this.isShowDel =
      this.$store.state.buttonLimitsArr.indexOf('depositSet:delete') > -1

    this.$set(this.formData, 'sectionType', '0')
    this.$set(this.rules, 'sectionType', [
      { required: true, message: '分段设置比例不能为空', trigger: 'blur' },
    ])
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
    this.$nextTick(() => {
      this.driver = new Driver({
        className: '', // className to wrap driver.js popover
        animate: true, // Animate while changing highlighted element
        opacity: 0.7, // Background opacity (0 means only popovers and without overlay)
        padding: 0, // Distance of element from around the edges
        allowClose: false, // Whether clicking on overlay should close or not
        overlayClickNext: false, // Should it move to next step on overlay click
        doneBtnText: '下一步', // Text on the final button
        closeBtnText: '', // Text on the close button for this step
        nextBtnText: '下一步', // Next button text for this step
        prevBtnText: '上一步', // Previous button text for this step
        onHighlighted: (Element) => {
          //当element完全突出显示时调用
          this.isDisabled = true
        },
        onReset: (Element) => {
          //当要清除覆盖时调用
          this.isDisabled = false
          localStorage.setItem('isPaymentRatio', false)
        },
        onNext: (Element) => {
          //下一步
          //  //如果点击缴纳银行的添加按钮则跳转到缴纳比例页面
          if (Element.options.element === '.addSecondTab') {
            this.skip()
          }
        },
      })
      if (localStorage.getItem('isPaymentRatio') != 'false' && this.fromTag) {
        //解决禁用出现空白问题
        this.isDisabled = true
        this.$nextTick(() => {
          this.driver.defineSteps(steps['three'])
          this.driver.start()
        })
      }
    })

    let that = this
    this.$nextTick(function () {
      let tableHeightCur = this.$refs.tableBox1.$el.clientHeight
      let tableTop = this.$refs.tableBox.getBoundingClientRect().top
      if (tableHeightCur + tableTop > window.innerHeight) {
        this.tableHeight =
          this.$refs.mainCon.getBoundingClientRect().height - 86
      } else {
        document.getElementsByClassName('tableBoxCur').length &&
          (document.getElementsByClassName('tableBoxCur')[0].style.height =
            window.innerHeight - tableTop - 40 + 'px')
      }

      window.onresize = function () {
        if (!that.$refs.tableBox1) {
          return
        }
        let tableHeightCur = that.$refs.tableBox1.$el.clientHeight
        let tableTop = that.$refs.tableBox.getBoundingClientRect().top
        if (tableHeightCur + tableTop > window.innerHeight) {
          that.tableHeight =
            that.$refs.mainCon.getBoundingClientRect().height - 86
        } else {
          document.getElementsByClassName('tableBoxCur').length &&
            (document.getElementsByClassName('tableBoxCur')[0].style.height =
              window.innerHeight - tableTop - 40 + 'px')
        }
      }
    })
  },
  activated() {
    window.addEventListener('scroll', this.handleScroll, true)
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
      this.$refs.tableBox1.doLayout()
    })
  },
  deactivated() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  beforeDestroy() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  methods: {
    handleRadio(val) {
      this.$set(this.formData, 'sectionType', '0')
    },
    handleScroll(e) {
      this.$nextTick(function () {
        //变量scrollTop是滚动条滚动时，距离顶部的距离
        var scrollTop = e.target.scrollTop
        if (
          this.$refs.tableBox &&
          this.$refs.tableBox.getBoundingClientRect().top < 128
        ) {
          this.tableHeight = window.innerHeight - 240
          if (document.getElementsByClassName('tableBoxCur').length) {
            document.getElementsByClassName('tableBoxCur')[0].style.height =
              null
          }
          this.hiddleToolBar = true
        } else {
          this.hiddleToolBar = false
        }
      })
    },
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    skip() {
      this.$router.push({
        name: 'cashDepositListJC',
        path: '/home/cashDeposit/cashDepositListJC',
        params: {
          paramsType: 'paymentRatio',
        },
      })
      this.$store.state.activeMenu = '/home/cashDeposit/cashDepositListJC'
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: this.oldUrl,
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    ...mapActions(['getAreas']),
    getTableList(data) {
      this.tableData = data
      this.loading = false
      this.getOrderNumber()
      if (this.tableData.length < 1) {
        this.isShow = true
      }
    },
    /**
     * @description: 校验缴纳比例
     */
    changeCount(value) {
      var regCost = /^(100|[1-9]\d|\d)(.\d{1,2})?$/
      if (!regCost.test(value) || value == 0.0 || value == 0.0 || value > 100) {
        this.$message({
          showClose: true,
          duration: 3000,
          message: '缴纳比例格式不正确',
          type: 'error',
        })
      }
    },
    /**
     * @description: 获取缴纳方式
     */
    getDepositTypeDesc() {
      this.axios({
        method: 'post',
        url: 'api-d/deposit/expand/method',
      })
        .then((res) => {
          this.depositTypeOptions = res.data.result
        })
        .catch((error) => {
          this.$message({
            showClose: true,
            duration: 3000,
            message: '获取缴纳方式失败',
            type: 'error',
          })
        })
    },
    // 获取相同编号的数组
    getOrderNumber() {
      let OrderObj = {}
      this.tableData.forEach((element, index) => {
        element.rowIndex = index
        if (OrderObj[element.areaId]) {
          OrderObj[element.areaId].push(index)
        } else {
          OrderObj[element.areaId] = []
          OrderObj[element.areaId].push(index)
        }
      })
      if (this.OrderIndexArr) {
        this.OrderIndexArr = []
      }
      // 将数组长度大于1的值 存储到this.OrderIndexArr（也就是需要合并的项）
      for (let k in OrderObj) {
        if (OrderObj[k].length > 1) {
          this.OrderIndexArr.push(OrderObj[k])
        }
      }
    },

    // 合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        for (let i = 0; i < this.OrderIndexArr.length; i++) {
          let element = this.OrderIndexArr[i]
          for (let j = 0; j < element.length; j++) {
            let item = element[j]
            if (rowIndex == item) {
              if (j == 0) {
                return {
                  rowspan: element.length,
                  colspan: 1,
                }
              } else if (j != 0) {
                return {
                  rowspan: 0,
                  colspan: 0,
                }
              }
            }
          }
        }
      }
    },
    // // 合并单元格过后的选中样式问题
    // tableRowClassName({ row, rowIndex }) {
    //   let arr = this.hoverOrderArr;
    //   for (let i = 0; i < arr.length; i++) {
    //     if (rowIndex == arr[i]) {
    //       return "aa";
    //     }
    //   }
    // },

    // cellMouseEnter(row, column, cell, event) {
    //   this.rowIndex = row.rowIndex;
    //   this.hoverOrderArr = [];
    //   this.OrderIndexArr.forEach(element => {
    //     if (element.indexOf(this.rowIndex) >= 0) {
    //       this.hoverOrderArr = element;
    //     }
    //   });
    // },

    // cellMouseLeave(row, column, cell, event) {
    //   this.rowIndex = "-1";
    //   this.hoverOrderArr = [];
    // },

    // 添加保证金缴纳比例
    addPaymentRatio() {
      this.isAdd = '1'
      this.dialogName = '添加保证金缴纳比例'
      this.disabled = false
      this.formVisible = true
      this.formData.costList = [{ min: '', max: '', scale: '' }]
      this.formData.maxCost = ''
      this.formData.noToPay = ''
      this.formData.yesPayOnline = ''
      this.formData.firstToPay = ''
      this.addAreaId = ''
      this.formData.noPayOnline = ''
      this.formData.scale = ''
      this.formData.radio = '1'
      this.hasShowReduce = false
      this.hasShowScaleReduce = false
      this.selectNo()
      this.formData.scaleArray = []
      this.formData.depositType = ''
      this.formData.scaleList = [{ scale: '' }]
      this.$nextTick(function () {
        this.$refs['formData'].clearValidate()
      })
    },

    // 保证金缴纳比例选择否的显示
    selectNo() {},
    addCostList(index) {
      //添加范围
      if (this.formData.costList.length > 8) {
        this.$message({
          message: '最多添加10条分段比例',
          type: 'warning',
        })
        return false
      } else {
        if (this.formData.costList[index].max) {
          this.formData.costList[index].max = ''
        }
        this.formData.costList.push({
          min: this.formData.costList[index].max,
          max: '',
          scale: '',
        })
      }
      this.hasShowReduce = true
    },
    /**
     * @description:添加缴纳比例
     */
    addScale(index) {
      //添加范围
      if (this.formData.scaleList.length > 2) {
        this.$message({
          message: '最多添加3条缴纳比例',
          type: 'warning',
        })
        return false
      } else {
        this.formData.scaleList.push({
          scale: '',
        })
      }
      this.hasShowScaleReduce = true
    },
    /**
     * @description: 删除缴纳比例
     */
    delScaleList(index) {
      //删除范围
      if (index == 1) {
        //第一条数据隐藏删除按钮
        this.hasShowScaleReduce = false
      }
      this.formData.scaleList.splice(index, 1)
      this.formData.scaleArray.splice(index, 1)
    },
    delCostList(index) {
      //删除范围
      if (index == 1) {
        //第一条数据隐藏删除按钮
        this.hasShowReduce = false
      }
      this.formData.costList.splice(index, 1)
    },

    assignmentCostMax(i) {
      //输入最大值实时赋值给下一条的最小值
      if (this.formData.costList[i + 1]) {
        this.formData.costList[i + 1].min = this.formData.costList[i].max
      }
    },
    inputMaxCost() {
      this.formData.costList[0].min = this.formData.maxCost
    },
    cancel(ele) {
      this.formVisible = false
      this.$refs[ele].resetFields()
    },
    closeDialog(ele) {
      this.$refs[ele].resetFields()
    },
    // 保存缴纳比例
    saveTopay(ele) {
      this.formData.scaleArray = []
      for (var i = 0; i < this.formData.scaleList.length; i++) {
        if (
          this.formData.scaleArray.indexOf(this.formData.scaleList[i].scale) ==
          -1
        ) {
          this.formData.scaleArray.push(this.formData.scaleList[i].scale)
        }
      }
      this.formData.costList[this.formData.costList.length - 1].max =
        '9999999999'
      this.$refs[ele].validate((valid, obj) => {
        if (valid) {
          this.getAreaAddress()
          var data
          if (this.formData.radio == '1') {
            data = {
              areaId: this.formData.addAreaId || this.Areas.AreaId, //---选择区域ID
              isSection: 0, //---是否分段(0：否，1：是)
              sectionType: 0,
              scale: this.formData.noToPay, //---缴纳比例
              depositType: this.formData.depositType, //---缴纳比例
              scaleArray: this.formData.scaleArray, //---缴纳比例
              upperLimit: this.formData.noPayOnline, // ---缴纳上限
            }
          } else {
            var firstData = [
              {
                min: '0',
                max: this.formData.maxCost,
                scale: this.formData.firstToPay,
              },
            ]
            firstData = firstData.concat(this.formData.costList)
            firstData[firstData.length - 1].max = '9999999999'
            data = {
              areaId: this.formData.addAreaId || this.Areas.AreaId,
              isSection: 1,
              upperLimit: this.formData.yesPayOnline,
              sectionType: this.formData.sectionType,
              depositConfigs: this.packageParams(firstData),
            }
          }
          if ((this.dialogName = '修改保证金缴纳比例')) {
            data.oldDepositType = this.oldDepositType
          }
          this.isSaveLoading = true
          if (this.isAdd == '1') {
            //添加保存
            this.addSuccess(data)
          } else {
            this.updateSuccess(data)
          }
        } else {
        }
      })
    },
    // 保存添加
    addSuccess(data) {
      this.axios({
        method: 'post',
        url: 'api-d/config/expand/add',
        data: data,
      })
        .then(
          (res) => {
            this.isSaveLoading = false
            if (!res.data.hasError) {
              this.formVisible = false
              this.$message({
                showClose: true,
                duration: 3000,
                message: '添加成功',
                type: 'success',
              })
              this.$refs.pagination.getTableListData()
            } else {
              this.$message({
                showClose: true,
                duration: 3000,
                message: res.data.errorMsg,
                type: 'error',
              })
            }
          },
          (res) => {
            this.isSaveLoading = false
            this.$message({
              showClose: true,
              duration: 3000,
              message: '添加失败',
              type: 'error',
            })
          }
        )
        .catch((error) => {
          this.isSaveLoading = false
        })
    },
    // 保存修改
    updateSuccess(data) {
      this.getAreas({ areaId: this.$store.state.areaInfoArr.areaId })
      this.axios({
        method: 'post',
        url: 'api-d/config/expand/edit',
        data: data,
      })
        .then(
          (res) => {
            this.isSaveLoading = false
            if (!res.data.hasError) {
              this.$message({
                showClose: true,
                duration: 3000,
                message: '修改成功',
                type: 'success',
              })
              var that = this
              that.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
              this.formVisible = false
            } else {
              this.$message({
                showClose: true,
                duration: 3000,
                message: res.data.errorMsg,
                type: 'error',
              })
            }
          },
          (res) => {
            this.isSaveLoading = false
            this.$message({
              showClose: true,
              duration: 3000,
              message: '修改失败',
              type: 'error',
            })
          }
        )
        .catch((error) => {
          this.isSaveLoading = false
        })
    },

    //获取选中的区域最后一级id
    getAreaId() {
      var areaId = this.areaId[this.areaId.length - 1]
      this.filterField.areaId = areaId
    },
    getCostAreaId() {
      var areaId = this.addAreaId[this.addAreaId.length - 1]
      this.formData.addAreaId = areaId
    },
    getAreaAddress() {
      let path = this.$refs.areas.getCheckedNodes()[0].path
      let address = this.$refs.areas.getCheckedNodes()[0].pathLabels
      this.Areas.AreaId = path[1]
      this.Areas.AreaName = address[0] + address[1]
      this.Areas.CityId = path[0]
      this.Areas.CityName = address[0]
      this.Areas.CountyId = path[1]
      this.Areas.CountyName = address[1]
    },
    // 删除数据
    delData(index, row) {
      this.$confirm('确认删除该数据吗?', '提示', {
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning',
      })
        .then(() => {
          this.axios({
            method: 'post',
            url: 'api-d/config/expand/delete',
            data: {
              areaId: row.areaId,
              depositType: row.depositType,
            },
          })
            .then(
              (response) => {
                if (!response.data.hasError) {
                  this.$message({
                    message: '删除成功',
                    type: 'success',
                  })
                  this.$refs.pagination.getTableListData(
                    this.pageNo,
                    this.pageSize
                  )
                } else {
                  this.$message({
                    message: response.data.errorMsg,
                    type: 'error',
                  })
                }
              },
              (response) => {}
            )
            .catch((error) => {})
        })
        .catch(() => {
          // this.$message.error("已取消");
        })
    },
    // 修改数据
    updateData(index, row) {
      this.isAdd = '2'
      this.dialogName = '修改保证金缴纳比例'
      this.disabled = true
      this.formVisible = true
      this.formData.costList = [{ min: '', max: '', scale: '' }]
      this.formData.maxCost = ''
      this.formData.noToPay = ''
      this.formData.yesPayOnline = ''
      this.formData.firstToPay = ''
      this.addAreaId = ''
      this.formData.noPayOnline = ''
      this.formData.radio = '1'
      this.formData.scaleArray = []
      this.formData.scaleList = [{ scale: '' }]
      this.formData.depositType = row.depositType
      this.oldDepositType = row.depositType
      this.hasShowReduce = false
      this.hasShowScaleReduce = false
      // 修改查询数据
      this.getUpdateData(row.areaId, row.depositType)
    },
    // 点击修改-查询数据
    getUpdateData(areaId, depositType) {
      this.axios({
        method: 'post',
        url: 'api-d/config/expand/initdata',
        data: {
          areaId: areaId,
          depositType: depositType,
        },
      })
        .then(
          (res) => {
            if (!res.data.hasError) {
              this.formData.sectionType = res.data.result.sectionType
                ? '1'
                : '0'
              if (res.data.result.isSectionDesc == '是') {
                this.formData.radio = '2'
                var newArr = []
                newArr = res.data.result.dcVOs
                this.formData.maxCost = newArr[0].max
                this.formData.firstToPay = newArr[0].scale
                this.formData.costList = newArr.slice(1)
                this.formData.yesPayOnline = res.data.result.upperLimit
              } else {
                let arr = []
                for (var i = 0; i < res.data.result.scaleArray.length; i++) {
                  let obj = {}
                  obj.scale = res.data.result.scaleArray[i]
                  arr.push(obj)
                }
                this.formData.scaleList = arr
                this.formData.radio = '1'
                this.formData.noPayOnline = res.data.result.upperLimit
                this.formData.noToPay = res.data.result.scale
              }
              if (this.formData.costList.length == 1) {
                this.hasShowReduce = false //数据只有一条的时候隐藏删除按钮
              } else {
                this.hasShowReduce = true
              }
              if (this.formData.scaleList.length == 1) {
                this.hasShowScaleReduce = false
              } else {
                this.hasShowScaleReduce = true
              }

              this.addAreaId = res.data.result.areaId
              this.formData.addAreaId = res.data.result.areaId
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    // 搜索
    searchList() {
      this.$refs.pagination.getTableListData()
    },
  },
}
</script>

<style lang="less" scoped>
@import '../../../static/css/filterArea.less';
.segmentSettingYes {
  padding: 20px 0;
  background: #f8f9fb;
  .unlimitInput {
    width: 25%;
    min-width: 160px;
  }
  .unlimitSty {
    /deep/.el-input__inner {
      border: 0;
      background: #f5f7fb;
    }
  }
  .buttonBox {
    position: absolute;
    right: 22px;
    top: 0px;
  }
}
.segmentSettingNo {
  margin-bottom: 22px;
  .projectCostBox {
    position: relative;
  }
  .unlimitInput {
    width: 25%;
    min-width: 160px;
  }
  .unlimitSty {
    /deep/.el-input__inner {
      border: 0;
      background: #f5f7fb;
    }
  }
}
.unit {
  padding-left: 8px;
}
.mB0 {
  margin-bottom: 0;
}
.mL18 {
  margin-left: 18px;
}
.mT12 {
  margin-top: 12px;
}
.mR12 {
  margin-right: 12px;
}
.ratioWidth {
  width: 310px;
}
/deep/.el-dialog {
  min-width: 800px;
}
// }
//引导页添加禁用样式
.addSecondTab.el-button.is-disabled {
  color: #fff;
  background-color: #009588;
  border-color: #009588;
}
.segmentTitle {
  padding: 0 20px;
  position: relative;
  line-height: 14px;
  color: #009588;
  margin-bottom: 20px;
  font-weight: 700;
}
.buttonBox {
  font-weight: normal;
  font-size: 14px;
  color: #009588;
  .el-link {
    margin-left: 15px;
  }
  .icon {
    margin-right: 4px;
    font-size: 14px;
  }
  span {
    font-size: 14px;
    cursor: pointer;
  }
}
.theme_default .segmentTitle {
  color: #409eff !important;
}
.theme_default .buttonBox {
  color: #409eff !important;
}
.icontianjia1 {
  color: #009588;
  margin-left: 5px;
}
.theme_default .icontianjia1 {
  color: #409eff !important;
}
/deep/.el-table td:first-child .cell {
  padding: 12px 16px !important;
}
</style>
